package com.bsb.biz.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.config.Const;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.SysOrganization;
import com.bsb.base.model.SysRole;
import com.bsb.base.model.SysRoleExample;
import com.bsb.base.model.SysRoleExample.Criteria;
import com.bsb.base.model.SysUser;
import com.bsb.biz.service.SysOrganizationService;
import com.bsb.biz.service.SysResourceService;
import com.bsb.biz.service.SysRoleDeptService;
import com.bsb.biz.service.SysRoleMenuService;
import com.bsb.biz.service.SysRoleService;
import com.bsb.biz.service.SysUserService;
import com.bsb.biz.shiro.UserUtils;



@Controller
@RequestMapping("/role")
public class SysRoleController{
	
	private int defaultPageSize=10;
	
	
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private SysResourceService sysResourceService;
	@Resource
	private SysOrganizationService sysOrganizationService;
	@Resource
	private SysRoleMenuService sysRoleMenuService;
	@Resource
	private SysRoleDeptService sysRoleDeptService;
	@Resource
	private SysUserService sysUserService;
	
	@RequiresPermissions("role:view")
	@RequestMapping(method = RequestMethod.GET)
	public String list(
			Model model,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		SysRoleExample sysRoleExample = new SysRoleExample();
		Criteria criteria = sysRoleExample.createCriteria();
		SysUser currentUser = UserUtils.currentUser();
		Long id = currentUser.getId();
		if(Const.SUPER_ADMIN != id){
			List<Long> deptIdsByUser = sysUserService.getDeptIdsByUser();
			List<String> depts = new ArrayList<String>();
			for (Long l : deptIdsByUser) {
				depts.add(l.toString());
			}
			criteria.andDept_idIn(depts);
		}
		int totalCount = sysRoleService.countSysRole(sysRoleExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		sysRoleExample.setPageIndex((pageNum - 1) * pageSize);
		sysRoleExample.setPageSize(pageSize);
		List<SysRole> sysRoles = sysRoleService.getPageSysRole(sysRoleExample);
		for (SysRole sysRole : sysRoles) {
			SysOrganization deptByRoleId = sysRoleService.getDeptByDeptId(sysRole.getDept_id());
			if(null != deptByRoleId){
				sysRole.setDept_name(deptByRoleId.getName());
			}
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("sysRoles", sysRoles);
		return "/role/list";
	}
	
	@RequiresPermissions("role:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		setCommonData(model);
        model.addAttribute("role", new SysRole());
        model.addAttribute("op", "新增");
        return "role/edit";
	}
	
	@RequiresPermissions("role:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model,RedirectAttributes redirectAttributes, @ModelAttribute("role") SysRole sysRole) {
		String dept_id = sysRole.getDept_id();
		if(StringUtils.isEmpty(dept_id)){
			setCommonData(model);
	        model.addAttribute("role", new SysRole());
	        model.addAttribute("op", "新增");
	        redirectAttributes.addFlashAttribute("msg", "所属部门不能为空");
	        return "redirect:/role/create";
		}
		String resource_ids = sysRole.getResource_ids();
		if(StringUtils.isEmpty(resource_ids)){
			setCommonData(model);
	        model.addAttribute("role", new SysRole());
	        model.addAttribute("op", "新增");
	        redirectAttributes.addFlashAttribute("msg", "功能权限不能为空");
	        return "redirect:/role/create";
		}
		String data_dept_ids = sysRole.getData_dept_ids();
		if(StringUtils.isEmpty(data_dept_ids)){
			setCommonData(model);
	        model.addAttribute("role", new SysRole());
	        model.addAttribute("op", "新增");
	        redirectAttributes.addFlashAttribute("msg", "数据权限不能为空");
	        return "redirect:/role/create";
		}
//		sysRoleService.addSysRole(sysRole);
		sysRoleService.addRole(sysRole);
		redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/role";
	}
	
	@RequiresPermissions("role:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute("role", sysRoleService.getSysRoleById(id));
        model.addAttribute("op", "删除");
        return "role/edit";
    }
	
	@RequiresPermissions("role:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		SysRole sysRoleById = sysRoleService.getSysRoleById(id);
//		sysRoleService.delSysRoleById(id);
		sysRoleService.delRole(sysRoleById);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/role";
    }

    private void setCommonData(Model model) {
    	//菜单权限
        model.addAttribute("resourceList", sysResourceService.selectByExample(null));
        //数据权限
        List<SysOrganization> subDeptList = sysOrganizationService.getSubDeptList();
		model.addAttribute("dataDeptList", subDeptList);
    }

	@RequiresPermissions("role:update")
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String toEdit(Model model,@PathVariable("id") Long id) {
		setCommonData(model);
		SysRole sysRole = sysRoleService.getSysRoleById(id);
		SysOrganization sysOrganizationById = sysOrganizationService.getSysOrganizationById(Long.valueOf(sysRole.getDept_id()));
		if(null != sysOrganizationById){
			sysRole.setDept_name(sysOrganizationById.getName());
		}
		List<Long> menuListByRoleId = sysRoleMenuService.getMenuListByRoleId(id);
		sysRole.setResourceIds(menuListByRoleId);  //菜单权限
		List<Long> deptListByRoleId = sysRoleDeptService.getDeptListByRoleId(id);
		sysRole.setData_dept_ids(StringUtils.join(deptListByRoleId.toArray(), ","));
		sysRole.setDatadeptIds(deptListByRoleId);
		model.addAttribute("role", sysRole);
		model.addAttribute("op", "修改");
        return "role/edit";
	}

	@RequiresPermissions("role:update")
	@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
	public String edit(Model model,RedirectAttributes redirectAttributes, @ModelAttribute("role") SysRole sysRole) {
		String dept_id = sysRole.getDept_id();
		if(StringUtils.isEmpty(dept_id)){
			setCommonData(model);
			model.addAttribute("role", sysRole);
			model.addAttribute("op", "修改");
	        redirectAttributes.addFlashAttribute("msg", "所属部门不能为空");
	        return "role/edit";
		}
		String resource_ids = sysRole.getResource_ids();
		if(StringUtils.isEmpty(resource_ids)){
			setCommonData(model);
			model.addAttribute("role", sysRole);
			model.addAttribute("op", "修改");
	        redirectAttributes.addFlashAttribute("msg", "功能权限不能为空");
	        return "role/edit";
		}
		String data_dept_ids = sysRole.getData_dept_ids();
		if(StringUtils.isEmpty(data_dept_ids)){
			setCommonData(model);
			model.addAttribute("role", sysRole);
			model.addAttribute("op", "修改");
	        redirectAttributes.addFlashAttribute("msg", "数据权限不能为空");
	        return "role/edit";
		}
//		sysRoleService.updateSysRole(sysRole);
		sysRoleService.updateRole(sysRole);
		redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/role";
	}

	@RequiresPermissions("role:view")
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public String view(Model model,
			@RequestParam(value = "id", required = true) Long id) {
		SysRole sysRole = sysRoleService.getSysRoleById(id);
		model.addAttribute("role", sysRole);
		return "/SysRole/view";
	}
	
	@RequiresPermissions("role:view")
	@RequestMapping(value = "/select/{dept_id}", method = RequestMethod.GET)
	@ResponseBody
	public Object selectRoles(@PathVariable("dept_id") Long dept_id){
//		Map<String,List<SysRole>> map = new HashMap<String,List<SysRole>>();
//		map.put("rolesByDeptid", rolesByDeptid);
		List<SysRole> rolesByDeptid = sysRoleService.getRolesByDeptid(dept_id);
		return rolesByDeptid;
	}
}
